package com.sdkj.job;

import com.sdkj.mapper.SetmealMapper;
import com.sdkj.pojo.Setmeal;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
public class CleanPicJob {
    @Resource
    private SetmealMapper setmealMapper;
    //定时任务，清理图片

    @Scheduled(cron = "0 0/2 * * * ?")  //设定执行任务的时间(每间隔2分钟执行一次)
    private  void  cleanTask() {
        //从数据库中获取图片信息
        List<Setmeal> setmeals = setmealMapper.selectList(null);
        List<String> dbimgs = new ArrayList<>();
        for (Setmeal setmeal : setmeals) {
            dbimgs.add(setmeal.getImg());
        }
        //获取磁盘中所有的图片名称
        String path = "F:/j_demo/photos/";
        File file = new File(path);
        File[] files = file.listFiles();//获取该路径下所有的文件
        List<String> list = new ArrayList<>();
        for (File newFile : files) {
            String name = newFile.getName();//获取文件名称
            if (name.endsWith(".jpg")) {
                list.add(name);
            }
        }
        //对比图片是否被数据库使用 如果没有使用从磁盘删除图片
        for (String fname : list) {
            //判断磁盘的图片名称是否在数据库中出现
            boolean contains = dbimgs.contains(fname);
            if (contains) {
                continue;
            } else {
                File delFile = new File(path + fname);
                delFile.delete();
            }
        }
    }
}
